package com.apes.crm.vip.masterdata.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.crm.vip.masterdata.model.VipGrade;
import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import com.apes.crm.vip.masterdata.model.VipIdentity;
import com.apes.crm.vip.masterdata.repository.VipIdentityRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: apes-server
 * @description
 * @author: czs
 * @create: 2021-04-09 11:02
 **/
@Service("vipIdentityService")
public class VipIdentityService extends DomainService {

    @Autowired
    VipIdentityRepository vipIdentityRepository;


    public List<Map> toSave(SimpleRequest request) {
        JSONObject jo = request.getJO();
        String method =jo.getString("method");

        JSONObject response = JSONObject.parseObject(this.invoke("pi.app.pub", MapUtil.mapper("headers",MapUtil.mapper("method",method,"action","get"),"body",new HashMap())));
        JSONArray array = response.getJSONArray("data");

        List<Map> list = array.stream().map(obj -> {
            JSONObject json = (JSONObject) obj;
            return MapUtil.mapper(
                    "id", json.getString("key"),
                    "name", json.getString("value"));
        }).collect(Collectors.toList());
        return list;
    }

    public void insertVipIdentity(SimpleRequest request){
        JSONObject jo = request.getJO();
        String id = jo.getString("id");
        String name = jo.getString("name");
        VipIdentity vipIdentity = Optional.ofNullable(vipIdentityRepository.findOne(id)).orElseGet(() -> request.getO(VipIdentity.class));
        vipIdentity.setId(id);
        vipIdentity.setName(name);
        vipIdentity.setRemark("定时同步");
        vipIdentityRepository.saveAndFlush(vipIdentity);
    }
}
